<!-- src/pages/ArticleList.vue -->
<template>
    <v-container>
      <v-row>
        <v-col cols="12" md="3">
          <v-select
            :items="categories"
            label="分类"
            v-model="selectedCategory"
            @update:modelValue="fetchArticles({category:selectedCategory})"
          ></v-select>
  
          <v-select
            :items="tags"
            item-title="name"
            item-value="id"
            label="标签"
            v-model="selectedTag"
            @update:modelValue="onTagChange"
          ></v-select>

          
  
        </v-col>
  
        <v-col cols="12" md="9">
          <v-list>
            <v-list-item v-for="article in paginatedArticles" :key="article.id"
            :subtitle="article.content"
            :title="article.title">  
              <v-list-item-action>
                <v-btn :to="`/articles/${article.id}`" text>阅读更多</v-btn>
  
              </v-list-item-action>
  
            </v-list-item>
  
          </v-list>
  
          <v-pagination
            v-model="page"
            :length="totalPages"
            @input="fetchArticles"
          ></v-pagination>
  
        </v-col>
  
      </v-row>
  
    </v-container>
  
  </template>
  
  <script>
  import { mapState, mapActions } from 'vuex'
  
  export default {
    name: 'ArticleList',
    data() {
      return {
        selectedCategory: null,
        selectedTag: null,
        page: 1,
        perPage: 10,
      }
    },
    computed: {
      ...mapState(['articles', 'categories', 'tags']),
      paginatedArticles() {
        const start = (this.page - 1) * this.perPage
        const end = start + this.perPage
        let filtered = this.articles
        return filtered.slice(start, end)
      },
      totalPages() {
        let filtered = this.articles
        return Math.ceil(filtered.length / this.perPage)
      },
    },
    created() {
      this.fetchArticles()
      this.fetchCategories()
      this.fetchTags()
      // console.log('初始 tags:', this.tags);
    },
    methods: {
      ...mapActions(['fetchArticles', 'fetchCategories', 'fetchTags']),
      onTagChange() {
        console.log('selectedTag:', this.selectedTag);
        this.page = 1 // 重置分页到第一页
        this.fetchArticles({ tag: this.selectedTag })
    },
    },
  }
  </script>
  